# routes.py
from flask import request, Blueprint, current_app
from models import db, User, WrongQuestion
from utils import success_response, failure_response, hash_password, check_hashed_password, generate_auth_token, \
    token_required
from services import generate_quiz, calculate_and_save_result, get_historical_stats
from sqlalchemy.exc import IntegrityError
from datetime import datetime

# 创建蓝图 (Blueprint) 来管理路由
api_bp = Blueprint('api', __name__, url_prefix='/api/v1')


# --- 认证与用户管理路由 ---

@api_bp.route('/auth/register', methods=['POST'])
def register_route():
    """1.1 用户注册"""
    try:
        current_app.logger.debug(f"[register_route] 收到请求数据: {request.json}")

        data = request.json
        username = data.get('username')
        password = data.get('password')
        child_name = data.get('child_name', '孩子')
        grade = data.get('grade', 1)

        if not username or not password:
            return failure_response(40003, 400)  # 缺少参数

        hashed_password = hash_password(password)
        new_user = User(username=username, password_hash=hashed_password, child_name=child_name, grade=grade)

        db.session.add(new_user)
        db.session.commit()
        return success_response({}, 201)

    except IntegrityError:
        db.session.rollback()
        return failure_response(40004, 409)  # 用户已存在
    except Exception:
        return failure_response(50099, 500)


@api_bp.route('/auth/login', methods=['POST'])
def login_route():
    """1.2 用户登录"""
    current_app.logger.debug(f"[login_route] 收到请求数据: {request.json}")

    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return failure_response(40003, 400)

    user = db.session.scalar(db.select(User).filter_by(username=username))

    if user and check_hashed_password(user.password_hash, password):
        token = generate_auth_token(user.id)
        current_app.logger.info(f"[login_route] 用户 {user.id} 登录成功，生成 Token。")
        return success_response({
            "token": token,
            "user_id": user.id
        })
    else:
        current_app.logger.warning(f"[login_route] 用户 {username} 登录失败: 用户名或密码错误。")
        return failure_response(40001, 401)  # 用户名或密码错误


@api_bp.route('/user/profile', methods=['GET'])
@token_required
def get_profile_route():
    """1.3 获取用户信息"""
    current_app.logger.debug(f"[get_profile_route] 认证成功，获取用户 ID: {request.user_id}")

    user = db.session.get(User, request.user_id)
    if not user:
        return failure_response(40002, 401)

    return success_response({
        "user_id": user.id,
        "username": user.username,
        "child_name": user.child_name,
        "grade": user.grade,
        "reminder_time": user.reminder_time,
        "created_at": user.created_at.isoformat()
    })


@api_bp.route('/user/getUserInfo', methods=['GET'])
@token_required
def get_user_info_route():
    """新增：获取用户信息（与/profile接口功能一致）"""
    current_app.logger.debug(f"[get_user_info_route] 认证成功，获取用户 ID: {request.user_id}")

    user = db.session.get(User, request.user_id)
    if not user:
        return failure_response(40002, 401)

    return success_response({
        "user_id": user.id,
        "username": user.username,
        "child_name": user.child_name,
        "grade": user.grade,
        "reminder_time": user.reminder_time,
        "created_at": user.created_at.isoformat()
    })


@api_bp.route('/user/reminder', methods=['POST'])
@token_required
def set_reminder_route():
    """1.4 设置提醒时间"""
    current_app.logger.debug(f"[set_reminder_route] 认证成功，用户 ID: {request.user_id}，收到数据: {request.json}")

    data = request.json
    reminder_time = data.get('reminder_time')

    if not reminder_time:
        return failure_response(40003, 400)

    try:
        user = db.session.get(User, request.user_id)
        if user:
            user.reminder_time = reminder_time
            db.session.commit()
            return success_response()
        return failure_response(40002, 401)
    except Exception as e:
        current_app.logger.error(f"[set_reminder_route] 数据库操作失败: {e}")
        return failure_response(50001, 500)


# --- 口算与统计路由 ---

@api_bp.route('/quiz/generate', methods=['GET'])
@token_required
def generate_quiz_route():
    """2.1 获取题目"""
    current_app.logger.debug(f"[generate_quiz_route] 认证成功，获取用户 ID: {request.user_id}")

    questions, err_code = generate_quiz(request.user_id)

    if err_code != 0:
        current_app.logger.error(f"[generate_quiz_route] 题目生成失败，错误码: {err_code}")
        return failure_response(err_code, 500)

    return success_response({
        "session_id": f"mock_session_{request.user_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}",
        "questions": questions
    })


@api_bp.route('/quiz/submit', methods=['POST'])
@token_required
def submit_quiz_route():
    """2.2 提交答案"""
    current_app.logger.debug(f"[submit_quiz_route] 认证成功，用户 ID: {request.user_id}，收到数据: {request.json}")

    data = request.json
    session_id = data.get('session_id')
    answers = data.get('answers')

    if not session_id or not answers:
        return failure_response(40003, 400)

    result, err_code = calculate_and_save_result(request.user_id, session_id, answers)

    if err_code != 0:
        current_app.logger.error(f"[submit_quiz_route] 结果保存失败，错误码: {err_code}")
        if err_code == 40003:
             return failure_response(err_code, 400) # 参数格式错误
        return failure_response(err_code, 500)

    return success_response(result)


@api_bp.route('/stats/daily', methods=['GET'])
@token_required
def get_daily_stats_route():
    """3.1 获取历史记录"""
    current_app.logger.debug(f"[get_daily_stats_route] 认证成功，用户 ID: {request.user_id}，收到参数: {request.args}")

    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')

    if not start_date or not end_date:
        return failure_response(40003, 400)  # 缺少日期参数

    records, err_code = get_historical_stats(request.user_id, start_date, end_date)

    if err_code != 0:
        if err_code == 40003:
            return failure_response(err_code, 400) # 日期格式错误
        return failure_response(err_code, 500)

    return success_response({"records": records})


@api_bp.route('/quiz/wrongbook', methods=['GET'])
@token_required
def get_wrongbook_route():
    """2.3 获取错题本"""
    current_app.logger.debug(f"[get_wrongbook_route] 认证成功，获取用户 ID: {request.user_id}")

    try:
        wrong_questions_query = db.session.scalars(
            db.select(WrongQuestion)
            .filter_by(user_id=request.user_id)
            .order_by(WrongQuestion.last_mistake_date.desc())
        ).all()

        wrong_questions = []
        for wq in wrong_questions_query:
            wrong_questions.append({
                "id": wq.id,
                "content": wq.content,
                "correct_answer": wq.correct_answer,
                "mistake_count": wq.mistake_count,
                "last_mistake_date": wq.last_mistake_date.isoformat()
            })

        return success_response({"wrong_questions": wrong_questions})
    
    except Exception as e:
        current_app.logger.error(f"[get_wrongbook_route] 查询错题本失败: {e}")
        return failure_response(50001, 500)